/**
 * 
 */
package com.bjtech.web.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.ssi.web.struts.BaseAction;

import com.bjtech.domain.User;
import com.bjtech.web.util.Constants;

/**
 * @author 
 *
 */
public abstract class LyheatBaseAction extends BaseAction {
	
	private static final long serialVersionUID = 2803043256698178065L;
	private static final String ENCODING_PREFIX = "encoding";
	private static final String NOCACHE_PREFIX = "no-cache";
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final boolean NOCACHE_DEFAULT = true;
	
	/**
	 * @param request
	 * @return -1：session过期；0：session正常。
	 */
	protected int isLogin() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Long UserID = null;
		String redirect = "/management";

		if (UserID == null && (session.getAttribute(Constants.CKMS) != null)) {
			UserID = ((User) session.getAttribute(Constants.CKMS)).getUserId();
		}
		if (UserID == null && (session.getAttribute(Constants.MANAGEMENT) != null)) {
			UserID = ((User) session.getAttribute(Constants.MANAGEMENT)).getUserId();
		}

		if (UserID == null) {
			if (request.getServletPath().startsWith("/ckms")) {
				redirect = request.getContextPath() + "/ckms/";
			} else if (request.getServletPath().startsWith("/management")) {
				redirect = request.getContextPath() + "/management/";
			} else {
				redirect = request.getContextPath() + "/index.html";
			}
			request.setAttribute("error", "您还没有登录！或者会话期已过，请重新登录！&nbsp;<a href=\"" + redirect + "\">登录</a>");
			return -1;
		}

		return 0;
	}

	public static User getUser() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(Constants.CKMS);
		if (user != null && user.getUserId() != null) {
			return user;
		}
		user = (User) session.getAttribute(Constants.MANAGEMENT);
		if (user != null && user.getUserId() != null) {
			return user;
		}
		user = (User) session.getAttribute(Constants.MANAGEMENT);
		if (user != null && user.getUserId() != null) {
			return user;
		}
		return null;
	}
	
	public static void render(final String contentType, final String content, final String[] headers) {
		try {
			//分析headers参数
			String encoding = ENCODING_DEFAULT;
			boolean noCache = NOCACHE_DEFAULT;
			for (int i=0;i<headers.length;i++) {
				String headerName = StringUtils.substringBefore(headers[i], ":");
				String headerValue = StringUtils.substringAfter(headers[i], ":");

				if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
					encoding = headerValue;
				} else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
					noCache = Boolean.parseBoolean(headerValue);
				} else{
					throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
				}
			}

			HttpServletResponse response = ServletActionContext.getResponse();

			//设置headers参数
			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			if (noCache) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
			}

			response.getWriter().write(content);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 直接输出文本.
	 * @see #render(String, String, String...)
	 */
	public static void renderText(final String text, final String[] headers) {
		render("text/plain", text, headers);
	}

	/**
	 * 直接输出HTML.
	 * @see #render(String, String, String...)
	 */
	public static void renderHtml(final String html, final String[] headers) {
		render("text/html", html, headers);
	}

	/**
	 * 直接输出XML.
	 * @see #render(String, String, String...)
	 */
	public static void renderXml(final String xml, final String[] headers) {
		render("text/xml", xml, headers);
	}

	/**
	 * 直接输出JSON.
	 * 
	 * @param string json字符串.
	 * @see #render(String, String, String...)
	 */
	public static void renderJson(final String string, final String[] headers) {
		render("text/json", string, headers);
	}

	/**
	 * 直接输出JavaScript
	 * @return
	 */
	
	
	public static void renderJavaScript(final String text){
		final String prefixJavaScript = "<script type=\"text/javascript\">";
		final String postfixJavaScript = "</script>";
		StringBuffer sb = new StringBuffer();
		sb.append(prefixJavaScript);
		sb.append(text);
		sb.append(postfixJavaScript);
		String[] header = {"encoding:UTF-8"};
		renderHtml(sb.toString(),header);
	}

}
